<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="studentID">
        <el-input
          v-model="queryParams.studentID"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级ID" prop="classID">
        <el-select
          v-model="queryParams.classID"
          style="width: 220px;"
          placeholder="请选择卓越班班级"
          clearable
          @keyup.enter="handleQuery">
          <el-option
            v-for="item in ClassInfoList"
            :key="item.id"
            :label="item.className"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="小组ID" prop="groupID">
        <el-select
          v-model="queryParams.groupID"
          placeholder="请选择小组ID"
          clearable
          style="width: 220px;"
          @keyup.enter="handleQuery">
          <el-option
            v-for="item in GroupsListByClass"
            :key="item.groupID"
            :label="item.groupName"
            :value="item.groupID"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Right"
          @click="handleView"
        >未分组
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupMembersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="stuName" width="75"/>
      <el-table-column label="学号" align="center" prop="studentID" />
      <el-table-column label="性别" align="center" prop="stuSex" width="75"/>
      <el-table-column label="班级" align="center" prop="stuClass"/>
      <el-table-column label="卓越班" align="center" prop="classID" >
        <template #default="scope">
          <span>{{CheekClass( scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="小组" align="center" prop="groupID" >
        <template #default="scope">
          <span>{{ CheekGroup(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="roleInGroup" width="75"/>
      <el-table-column label="年级" align="center" prop="stuGrade" width="75"/>
      <el-table-column label="加入时间" align="center" prop="joinDate" width="120">
        <template #default="scope">
          <span>{{scope.row.joinDate}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 40]"
      @size-change="getList"
      @current-change="getList"
      class="custom-pagination"
    />

    <!-- 添加或修改小组成员对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="groupmembersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生" prop="studentID">
          <el-input v-model="form.studentID" placeholder="请输入学生ID" style="width: 220px" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="小组" prop="groupID">
          <el-select v-model="form.groupID" placeholder="请输入小组ID" style="width: 220px">
            <el-option
              v-for="item in GroupsListByClass"
              :key="item.groupID"
              :label="item.groupName"
              :value="item.groupID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GroupMembers" lang="ts">
import {
  addGroupMembers,
  delGroupMembers, exportGroupMembers,
  getGroupMembers,
  listGroupMembers,
  updateGroupMembers
} from '@/apis/system/groupMembers'
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listGroups } from '@/apis/system/groups'
import { listClassinfo } from '@/apis/system/classinfo'
import router from '@/router'
import { GroupStore } from '@/stores/group'
import {exportClass} from "@/apis/system/classMembers";

const groupStore = GroupStore()
const { proxy } = getCurrentInstance() as { proxy: any }

const groupMembersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {
    groupMemberID: null,
    studentID: null,
    groupID: null,
    classID: null,
    roleInGroup: null,
    joinDate: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentID: null,
    groupID: null,
    classID: null,
    roleInGroup: null,
    joinDate: null
  },
  rules: {
    studentID: [
      { required: true, message: '学生ID不能为空', trigger: 'blur' }
    ],
    groupID: [
      { required: true, message: '小组ID不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
const GroupsList = ref< any[]>([]);
const GroupsListByClass = ref<any[]>([]);
const GroupsQueryParams= ref({
  pageNum: 1,
  pageSize: 100000000,
  classID: null,
})
function CheekGroup(row: any){
  for(let i=0;i<GroupsList.value.length;i++){
    if(row.groupID===GroupsList.value[i].groupID){
      return GroupsList.value[i].groupName
    }
  }
}
listGroups(GroupsQueryParams.value).then(response => {
  if(response.data.code===200){
    GroupsList.value = response.data.data.records
    GroupsListByClass.value=response.data.data.records
  }else {
    ElMessage({ message: response.data.msg, type: 'error'})
  }
})
//如果queryParams.value.classID变化，则根据classID查询小组信息
watch(
  () => queryParams.value.classID,
  () => {
    GroupsListByClass.value=GroupsList.value.filter((item:any)=>{
      if(queryParams.value.classID==null)return true;
      return item.classID===queryParams.value.classID
    })
  }
)
const ClassInfoList = ref< any[]>([]);
const ClassInfoQueryParams= ref({
  pageNum: 1,
  pageSize: 100000000,
})
listClassinfo(ClassInfoQueryParams.value).then(response => {
  if(response.data.code===200){
    ClassInfoList.value = response.data.data.records;
    total.value = response.data.data.total;
  }else {
    ElMessage({ message: response.data.msg, type: 'error'})
  }
});
function CheekClass(row:any) {
  for(let i=0;i<ClassInfoList.value.length;i++){
    if(row.classID===ClassInfoList.value[i].id){
      return ClassInfoList.value[i].className
    }
  }
}
/** 查询小组成员列表 */
function getList() {
  loading.value = true
  listGroupMembers(queryParams.value).then(response => {
    if(response.data.code===200){
      groupMembersList.value = response.data.data.records
      total.value = response.data.data.total
    }else {
      ElMessage({ message: response.data.msg, type: 'error'})
    }
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  GroupsListByClass.value=GroupsList.value;
  reset()
}

// 表单重置
function reset() {
  form.value = {
    classID: null,
    groupMemberID: null,
    studentID: null,
    groupID: null,
    roleInGroup: null,
    joinDate: null
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    studentID: null,
    groupID: null,
    classID: null,
    roleInGroup: null,
    joinDate: null
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map(item => item.groupMemberID)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
  reset()
  const _GroupMemberID = row.groupMemberID || ids.value
  GroupsListByClass.value=GroupsList.value.filter((item:any)=>{
    if(row.classID==null)return true;
    return item.classID===row.classID
  })
  getGroupMembers(_GroupMemberID).then(response => {
    if (response.data.code===200) {
      form.value = response.data.data
    }else {
      ElMessage({ message: response.data.msg, type: 'error'})
    }
    open.value = true
    title.value = '修改小组成员'
  })
}

function handleView() {
  groupStore.groupInfo.OriginGroupPath = router.currentRoute.value.path
  router.push({ path: '/Group/NotGroupMembersManager' })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['groupmembersRef'].validate((valid: boolean) => {
    if (valid) {
      if (form.value.groupMemberID != null) {
        updateGroupMembers(form.value).then(response => {
          if(response.data.code===200){
            ElMessage({ message: '修改成功', type: 'success'})
          }else {
            ElMessage({ message: response.data.msg, type: 'error'})
          }
          open.value = false
          GroupsListByClass.value=GroupsList.value;
          getList()
          reset()
        })
      } else {
        addGroupMembers(form.value).then(response => {
          if (response.data.code===200){
            ElMessage({ message: '新增成功', type: 'success'})
          }else {
            ElMessage({ message: response.data.msg, type: 'error'})
          }
          open.value = false
          getList()
          reset()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row: any) {
  const _GroupMemberIDs = row.groupMemberID || ids.value
  ElMessageBox.alert('是否确认删除？', '提示', {
    confirmButtonText: '确定',
    callback: (action: string) => {
      if (action === 'confirm') {
        delGroupMembers(_GroupMemberIDs).then(response => {
          if(response.data.code === 200){
            ElMessage({ type: 'success', message: '删除成功' })
          }else{
            ElMessage({ type: 'error', message: response.data.msg })
          }
          getList();
        })
      }
    }
  });
}

// 时间格式化
function formatDateToYYYYMMDDHHMMSS(timestamp: number): string {
  const date = new Date(timestamp);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/** 导出按钮操作 */
function handleExport() {
  const size = queryParams.value.pageSize;
  queryParams.value.pageSize = Number(1e9);
  exportGroupMembers(queryParams.value).then(
      res => {
        const link = document.createElement('a');
        try {
          let blob = res.data;
          let _fileName = formatDateToYYYYMMDDHHMMSS(Date.now()) + '.xlsx';
          link.style.display = 'none';
          const url = window.URL.createObjectURL(blob);
          link.href = url;
          link.download = _fileName;
          link.click();
          window.URL.revokeObjectURL(url);
          //显示弹窗，提示正在导出，请稍等
          ElMessage({ type: 'success', message: '正在导出，请稍等' })
        } catch (e) {
          console.log('下载的文件出错', e);
        }
      }
  );
  queryParams.value.pageSize=size;
}

getList()
</script>

<style scoped>
.custom-pagination {
  margin-top: 20px; /* 调整分页组件与表格的间距 */
  display: flex;
  justify-content: center; /* 居中对齐分页组件 */
}

.custom-pagination .el-pagination__total,
.custom-pagination .el-pagination__sizes,
.custom-pagination .el-pager li,
.custom-pagination .btn-prev,
.custom-pagination .btn-next,
.custom-pagination .el-pagination__jump {
  font-size: 14px; /* 调整字体大小 */
  color: #333; /* 调整文字颜色 */
}

.custom-pagination .el-pagination__sizes .el-input .el-input__inner {
  height: 30px; /* 调整输入框高度 */
  line-height: 30px; /* 调整输入框行高 */
}

.custom-pagination .el-pager li {
  min-width: 30px; /* 调整分页按钮最小宽度 */
  height: 30px; /* 调整分页按钮高度 */
  line-height: 30px; /* 调整分页按钮行高 */
  background-color: #f5f7fa; /* 调整分页按钮背景颜色 */
  border-radius: 4px; /* 调整分页按钮圆角 */
  margin: 0 5px; /* 调整分页按钮间距 */
}

.custom-pagination .el-pager li.active {
  background-color: #409eff; /* 调整激活分页按钮背景颜色 */
  color: #fff; /* 调整激活分页按钮文字颜色 */
}

.custom-pagination .btn-prev,
.custom-pagination .btn-next {
  height: 30px; /* 调整前后按钮高度 */
  line-height: 30px; /* 调整前后按钮行高 */
  background-color: #f5f7fa; /* 调整前后按钮背景颜色 */
  border-radius: 4px; /* 调整前后按钮圆角 */
  margin: 0 5px; /* 调整前后按钮间距 */
}

.custom-pagination .btn-prev:hover,
.custom-pagination .btn-next:hover {
  background-color: #409eff; /* 调整前后按钮悬停背景颜色 */
  color: #fff; /* 调整前后按钮悬停文字颜色 */
}
</style>
